package com.financial.service.integralpay.service.impl;

import com.financial.service.integralpay.connector.FinancialPlatformPayFegin;
import com.financial.service.integralpay.connector.FinancialYsPayFegin;
import com.financial.service.integralpay.constants.FinancialPayConfigEnumConstants;
import com.financial.service.integralpay.constants.FinancialPlatfromConfigEnumConstants;
import com.financial.service.integralpay.constants.FinancialReceiptBalancepayEnumConstants;
import com.financial.service.integralpay.dao.FinancialIntegralAgencypayReceiptDao;
import com.financial.service.integralpay.domain.FinancialIntegralAgencypayReceiptDO;
import com.financial.service.integralpay.service.FinancialIntegralAgencyPayService;
import com.financial.service.integralpay.utils.apiresult.ApiResult;
import com.financial.service.integralpay.utils.balanceutils.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Map;

@Service
public class FinancialIntegralAgencyPayServiceImpl implements FinancialIntegralAgencyPayService {
    public static final Logger logger = LoggerFactory.getLogger(FinancialIntegralAgencyPayServiceImpl.class);

    @Autowired
    private FinancialYsPayFegin yspayFegin;
    @Autowired
    private FinancialPlatformPayFegin platformPayFegin;
    @Autowired
    private FinancialIntegralAgencypayReceiptDao gyintegralAgencypayReceiptDao;

    @Override
    public Map<String, Object> integralAgencypay(Map<String, Object> requestMap) {
        logger.info("金融中心接收团购优店积分代付参数" + JsonUtils.objectToJson(requestMap));
        Map<String, Object> map = null;
        String outTradeNo = requestMap.get("outTradeNo").toString();
        String integralAmount = requestMap.get("integralAmount").toString();
        String subject = requestMap.get("subject").toString();
        String bankName = requestMap.get("bankName").toString();
        String bankCity = requestMap.get("bankCity").toString();
        String bankAccountName = requestMap.get("bankAccountName").toString();
        String bankCardType = requestMap.get("bankCardType").toString();
        String bankAccountType = requestMap.get("bankAccountType").toString();
        String bankAccountNo = requestMap.get("bankAccountNo").toString();
        String platfromMarking = requestMap.get("platfromMarking").toString();
        String payType = requestMap.get("payType").toString();

        //获取平台id
        int platfromId = platformPayFegin.getPlatfromId(platfromMarking);
        int channelsId = platformPayFegin.getChannelsId(payType);
        if (StringUtils.isEmpty(outTradeNo) || StringUtils.isEmpty(integralAmount)
                || StringUtils.isEmpty(bankAccountNo)
                || StringUtils.isEmpty(subject) ||
                StringUtils.isEmpty(bankName) || StringUtils.isEmpty(bankCity)
                || StringUtils.isEmpty(bankAccountName) || StringUtils.isEmpty(bankCardType)
                || StringUtils.isEmpty(bankAccountType)) {
            return ApiResult.paramIsNull();
        }
        requestMap.put("platfromId", String.valueOf(platfromId));
        requestMap.put("channelsId", String.valueOf(channelsId));
        requestMap.put("platfromMarking", platfromMarking);
        //"02"代表积分代付
        requestMap.put("payment_type", payType);
        requestMap.put("platfromId", String.valueOf(platfromId));
        try {
            map = yspayFegin.transferAccounts(requestMap);
            logger.info("积分代付调用银盛回执信息" + JsonUtils.objectToJson(map));
            if (null != map) {
                map.put("outTradeNo", outTradeNo);
                map.put("platfromId", platfromId);
                map.put("subject", subject);
                saveIntegralReceipt(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("out_trade_no:{},积分代付请求银盛失败:{}", outTradeNo, e.getMessage());
        }
        return map;
    }

    @Override
    public Map<String, Object> disposeIntegralasynPay(Map<String, Object> result) {
        logger.info("金融中心积分支付接受银盛代付异步回执消息"+ JsonUtils.objectToJson(result));
        String platfromId = result.get("platfromId").toString();
        String outTradeNo = result.get("out_trade_no").toString();
        String tradeStatus = result.get("trade_status").toString();
        String totalAmount = result.get("total_amount").toString();
        FinancialIntegralAgencypayReceiptDO receiptDO = new FinancialIntegralAgencypayReceiptDO();
        receiptDO.setIsDelete(FinancialPlatfromConfigEnumConstants.ENUM_ISDELETE_UNDEL);
        receiptDO.setCode("10000");
        receiptDO.setMsg("交易成功");
        receiptDO.setTotalAmount(new BigDecimal(totalAmount));
        receiptDO.setTradeStatus(tradeStatus);
        receiptDO.setResponseType(FinancialReceiptBalancepayEnumConstants.ENUM_RESPONSETYPE_ASYNC);
        receiptDO.setGmtModified(new Date());
        receiptDO.setGmtCreate(new Date());
        receiptDO.setPlatfromappid(platfromId);
        receiptDO.setSubject("异步回执");
        receiptDO.setOutTradeNo(outTradeNo);
        gyintegralAgencypayReceiptDao.save(receiptDO);
        return result;
    }

    @Override
    public Map<String, Object> integralQuery(Map<String, Object> requestMap) {
        logger.info("接收优店financial主动查询金融中心积分代付参数"+JsonUtils.objectToJson(requestMap));
        Object temp = null;
        temp = requestMap.get("out_trade_no");
        String outTradeNo = temp != null ?temp.toString():null;
        temp = requestMap.get("shopdate");
        String shopdate = temp != null ?temp.toString():null;
        temp = requestMap.get("platfromMarking");
        String platfromMarking = temp != null ?temp.toString():null;
        temp = requestMap.get("payType");
        String payType = temp != null ?temp.toString():null;
        if(StringUtils.isEmpty(outTradeNo)||StringUtils.isEmpty(shopdate)
                ||StringUtils.isEmpty(platfromMarking)||StringUtils.isEmpty(payType)){
            return ApiResult.paramIsNull();
        }
        //根据平台标识获取id
        int platfromId = platformPayFegin.getPlatfromId(platfromMarking);
        //根据支付通道获取id
        int channelsId = platformPayFegin.getChannelsId(payType);
        requestMap.put("platfromId",String.valueOf(platfromId));
        requestMap.put("channelsId",String.valueOf(channelsId));
        Map<String, Object> resultMap = null;
        try {
            resultMap = yspayFegin.paymentQuery(requestMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("金融中心主动查询积分代付调用银盛失败:{}",e.getMessage());
        }
        return resultMap;
    }

    private void saveIntegralReceipt(Map<String,Object> map) {
        logger.info("金融中心保存积分代付回执"+JsonUtils.objectToJson(map));
        String outTradeNo = "";
        FinancialIntegralAgencypayReceiptDO gyintegralAgencypayReceiptDO = new FinancialIntegralAgencypayReceiptDO();
        try{
            String code = map.get("code").toString();
            String subject = map.get("subject").toString();
            outTradeNo = map.get("outTradeNo").toString();
            String platfromId = map.get("platfromId").toString();
            if (code.equals("10000")) {
                //保存积分代付回执信息
                String msg = map.get("msg").toString();
                String tradeStatus = map.get("trade_status").toString();
                gyintegralAgencypayReceiptDO.setCode(code);
                gyintegralAgencypayReceiptDO.setMsg(msg);
                gyintegralAgencypayReceiptDO.setSubject(subject);
                gyintegralAgencypayReceiptDO.setGmtCreate(new Date());
                gyintegralAgencypayReceiptDO.setGmtModified(new Date());
                gyintegralAgencypayReceiptDO.setIsDelete(FinancialPayConfigEnumConstants.ENUM_ISDELETE_UNDEL);
                gyintegralAgencypayReceiptDO.setOutTradeNo(map.get("out_trade_no").toString());
                gyintegralAgencypayReceiptDO.setPlatfromappid(platfromId);
                gyintegralAgencypayReceiptDO.setResponseType(FinancialReceiptBalancepayEnumConstants.ENUM_RESPONSETYPE_SYNC);
                gyintegralAgencypayReceiptDO.setTradeStatus(tradeStatus);
                gyintegralAgencypayReceiptDO.setTotalAmount(new BigDecimal(map.get("total_amount").toString()).setScale(2, RoundingMode.HALF_UP));
                gyintegralAgencypayReceiptDao.save(gyintegralAgencypayReceiptDO);
            } else {
                String subMsg = map.get("sub_msg").toString();
                gyintegralAgencypayReceiptDO.setCode(code);
                gyintegralAgencypayReceiptDO.setMsg(subMsg);
                gyintegralAgencypayReceiptDO.setSubject(subject);
                gyintegralAgencypayReceiptDO.setGmtCreate(new Date());
                gyintegralAgencypayReceiptDO.setGmtModified(new Date());
                gyintegralAgencypayReceiptDO.setIsDelete(FinancialPayConfigEnumConstants.ENUM_ISDELETE_UNDEL);
                gyintegralAgencypayReceiptDO.setOutTradeNo(outTradeNo);
                gyintegralAgencypayReceiptDO.setPlatfromappid(platfromId);
                gyintegralAgencypayReceiptDO.setResponseType(FinancialReceiptBalancepayEnumConstants.ENUM_RESPONSETYPE_SYNC);
                gyintegralAgencypayReceiptDO.setTradeStatus("TRADE_ACCEPT_FAIL");
                gyintegralAgencypayReceiptDao.save(gyintegralAgencypayReceiptDO);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("订单号outTradeNo:{},积分代付保存失败:{}",outTradeNo,e.getMessage());
        }

    }

}
